import { Injectable } from '@angular/core'
import {
  IPostRiskEventSchemePagination,
  PostRiskEventScheme,
  IPostRiskEventQueryParams,
  PostRiskEventRule,
  IRiskControlBiz,
  IPostRiskEventRuleTrade,
  IPostRiskEventRuleTradePagination,
  IPostRiskEventRuleTradeQueryParams,
  IPostRiskEventDetailQueryParams
} from '@shared/interfaces/postRisk-event'
import { ITrade } from '@shared/interfaces/trade'
import { Observable, throwError } from 'rxjs'
import { COMB_URL, COMB_URL2 } from 'app/utils/contraints'
import { HttpClient } from '@angular/common/http'
import { preProcessParams, encodeParams } from '@shared/decorators'
import { catchError, map, tap } from 'rxjs/operators'

@Injectable()
export class PostRiskEventService {
  constructor(private http: HttpClient) {}

  @preProcessParams()
  @encodeParams()
  getList(queryParams: IPostRiskEventQueryParams, str?: string): Observable<IPostRiskEventSchemePagination> {
    const url = `${COMB_URL}/camel/postrisk/events?${str}`
    return this.http.get<IPostRiskEventSchemePagination>(url)
  }

  getOne(queryParams: IPostRiskEventDetailQueryParams): Observable<PostRiskEventScheme> {
    // const url = `${COMB_URL}/camel/risk/scheme/${postRiskEventId}`
    const url = `${COMB_URL}/camel/postrisk/event/${queryParams.eventID}?intStoreCode=${queryParams.intStoreCode}`
    return this.http.get<PostRiskEventScheme>(url, { withCredentials: true})
  }
  updateRuleTrade(updateParams): Observable<IPostRiskEventRuleTrade> {
    const url = `${COMB_URL}/camel/postrisk/trades/${updateParams.eventTransID}?remark=${updateParams.remark}`
    return this.http.post<IPostRiskEventRuleTrade>(url, updateParams)
  }

  @preProcessParams()
  @encodeParams()
  getRuleTrades(queryParams: IPostRiskEventRuleTradeQueryParams, str?: string): Observable<IPostRiskEventRuleTradePagination> {
    const url = `${COMB_URL}/camel/postrisk/trades/${queryParams.eventRuleID}?${str}`
    return this.http.get<IPostRiskEventRuleTradePagination>(url)
  }

  getBizs(postRiskEventId: string): Observable<IRiskControlBiz[]> {
    const url = `${COMB_URL}/camel/risk/scheme/${postRiskEventId}/biz`
    return this.http.get<IRiskControlBiz[]>(url)
  }

  createRule(postRiskEventId: string, body: PostRiskEventRule): Observable<boolean> {
    const url = `${COMB_URL}/camel/risk/scheme/${postRiskEventId}/rule`
    return this.http
      .post<boolean>(url, body, {
        observe: 'response',
      })
      .pipe(
        map(resp => {
          const { status } = resp
          return true
        }),
      )
  }

  updateStatus(updateParams): Observable<any> {
    const url = `${COMB_URL}/camel/postrisk/event/${updateParams.eventId}`
    return this.http.post<any>(url, {status: updateParams.status})
      .pipe(map(res => {
        if (res.code === 'MSG_CODE.SYSTEM.SUCCESS') {
          return true
        }
        return false
      }))
  }
}
